package controller

import (
	"biz_alert/dao"
	"biz_alert/pkg/send_message"
	"fmt"
	"go.uber.org/zap"
	"gorm.io/gorm"
)

type BizExceptionControllerInterface interface {
	GetBizException() (string, error)
	SendMessageToWechat(string, string) error
}

type BizExceptionControllerImpl struct {
	logger *zap.Logger
	db     *gorm.DB
}

var NewBizExceptionControllerImpl = func(db *gorm.DB) BizExceptionControllerInterface {
	return &BizExceptionControllerImpl{
		db:     db,
		logger: zap.L().Named("biz_exception_controller"),
	}
}

func (b *BizExceptionControllerImpl) GetBizException() (res string, err error) {
	BizExceptionDao := dao.NewBizExceptionDaoImpl(b.db)
	total, err := BizExceptionDao.Total()
	if err != nil {
		b.logger.Error("get biz_exception count err", zap.Error(err))
		return "", err
	}
	if total == 0 {
		b.logger.Info("查询biz_exception中无数据")
		return "暂无业务异常, biz_exception无数据", nil
	}

	bzs, err := BizExceptionDao.GetException()
	if err != nil {
		b.logger.Error("查询biz_exception错误", zap.Error(err))
		return "", err
	}
	for _, result := range bzs {
		res += fmt.Sprintf("业务日期: %s, 业务异常消息: %s\n", result.Date1, result.ExceptionMsg)
	}
	res = fmt.Sprintf("[业务Alert]\n%s", res)
	return res, nil
}

func (b *BizExceptionControllerImpl) SendMessageToWechat(webhook, data string) error {
	err := send_message.SendMessageToWechat(webhook, data)
	if err != nil {
		b.logger.Sugar().Errorf("SendMessageToWechat failed: %s", err.Error())
		return err
	}
	b.logger.Sugar().Info("send message to wechat success!")
	return nil
}
